<?php

require_once 'CInput.php';

global $_CStringCreators;
$_CStringCreators = array();

global $_CEncoderCreators;
$_CEncoderCreators = array();

function CEncodingAdd($encodingNames, $stringClass, $encoderClass) {
	global $_CStringCreators, $_CEncoderCreators;
	
	foreach ($encodingNames as $name) {
		$name = strtoupper($name);
		$_CStringCreators[$name] = $stringClass;
		$_CEncoderCreators[$name] = $encoderClass;
	}
}

function CEncodingGetStringClass($encoding) {
	$encoding = strtoupper($encoding);
	global $_CStringCreators;
	
	return @$_CStringCreators[$encoding];
}

function CEncodingGetEncoderClass($encoding) {
	$encoding = strtoupper($encoding);
	global $_CEncoderCreators;
	
	return @$_CEncoderCreators[$encoding];
}

function CStringCreateFromBuffer($buffer, $encoding) {
	$s = CEncodingGetStringClass($encoding);
	if (is_null($s)) return null;
	
	return call_user_func(array($s, 'MakeNewFromBuffer'), $buffer);
}

function &CEncoderCreateOfEncoding($encoding, $allowLoss = null) {
	$e = CEncodingGetEncoderClass($encoding);
	if (is_null($e)) return null;
	
	$enc = &new $e($allowLoss);
	return $enc;
}

global $_CDefaultOutputEncoding;
$_CDefaultOutputEncoding = null;

function CEncodingSetOutput($enc) {
	global $_CEncoderCreators, $_CDefaultOutputEncoding;
	if (!array_key_exists($enc, $_CEncoderCreators)) {
		trigger_error("Encoding '$enc' cannot be used to produce output (support missing?)", E_USER_ERROR);
		return;
	}
	
	$_CDefaultOutputEncoding = $enc;
}

function CEncodingGetOutput() {
	$x = $GLOBALS['_CDefaultOutputEncoding'];
	if (is_null($x))
		return 'UTF-8';
	else
		return $x;
}

function CEncodingGetInput() {
	global $_CStringCreators;
	$x = CGetBuffer('_charset_');
	if ($x !== null && $x != 'x-default' && $x != '') {
		if (isset($_CStringCreators[strtoupper($x)]))
			return $x;
		else
			return null;
	} else
		return CEncodingGetOutput();
}

?>